<template>
	<div>
		<div class="TopTitle" slot="header">
			<div class="fl">
				<b>新增月度备忘</b>
			</div>
			<div class="fr">
				<el-button
					type="primary"
					size="mini"
					style="background: #7f92f7; border-color: #7f92f7"
					@click="handle_submit"
					>提交</el-button
				>
				<!-- <el-button
					type="danger"
					size="mini"
					style="background: #7ed093; border-color: #7ed093"
					@click="saveAction(1)"
					>发布</el-button
				> -->
				<el-button
					type="primary"
					size="mini"
					style="background: #fff; border-color: #5b5b5b; color: #5b5b5b"
					@click="$router.back()"
					>返回</el-button
				>
			</div>
    </div>
		<div class="centerForm">
			<el-form ref="form" :model="formData" :rules="rules" label-position="right" label-width="200px" size="small">
				<el-form-item prop="proTime" label="月份：">
					<el-date-picker
						v-model="formData.proTime"
						format="yyyy-MM"
						type="month"
						value-format="yyyyMM"
						placeholder="选择月"
						style="width: 200px"
						clearable
					></el-date-picker>
				</el-form-item>
				<el-form-item prop="abStract" label="摘要：">
					<el-input v-model="formData.abStract" style="width: 350px" clearable></el-input>
				</el-form-item>
				<el-form-item prop="invAmt" label="涉及总金额（税后，万元）：">
					<el-input v-model="formData.invAmt" oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g,'$1')" style="width: 350px" clearable></el-input>
				</el-form-item>
				<el-form-item prop="invAmtThisYear" label="涉及本年金额（税后，万元）：">
					<el-input v-model="formData.invAmtThisYear" oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g,'$1')" style="width: 350px" clearable></el-input>
				</el-form-item>
				<el-form-item prop="invAreaName" label="涉及区域：">
					<AreaCascader :area_name.sync="formData.invAreaName" :area_id.sync="formData.invAreaId" style="width: 350px" ref="areaCascader" />
				</el-form-item>
				<el-form-item prop="invSubCode" label="涉及科目：">
					<el-input v-model="formData.invSubCode" style="width: 350px" clearable></el-input>
				</el-form-item>
				<el-form-item prop="invIncomeType" label="涉及收入分类：">
					<el-input v-model="formData.invIncomeType" style="width: 350px" clearable></el-input>
				</el-form-item>
				<el-form-item prop="invAcctMonth" label="涉及月份：">
				<MonthsPicker :monthsValue.sync="formData.invAcctMonth"></MonthsPicker>
				</el-form-item>
				<el-form-item prop="moreInfo" label="涉及内容补充：">
					<el-input v-model="formData.moreInfo" style="width: 350px" clearable></el-input>
				</el-form-item>
				<el-form-item prop="admitPerson" label="录入人：">
					<el-input 
						:value="formData.admitPerson" 
						style="width: 350px" 
						disabled
					></el-input>
				</el-form-item>
				<el-form-item prop="eventTrigger" label="事项触发者：">
					<el-input v-model="formData.eventTrigger" style="width: 350px" clearable></el-input>
				</el-form-item>
				<el-form-item prop="dispatchFlag" label="是否需要派单：">
					<el-select v-model="formData.dispatchFlag" style="width: 350px" clearable>
						<el-option label="派单" value="派单"></el-option>
						<el-option label="不派单" value="不派单"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item prop="dispatchId" label="派发对象：">
					<el-select 
						v-model="formData.dispatchId" 
						:placeholder="userOptions.length == 0 ? '请先选择涉及区域' : '请选择'"
						style="width: 350px" 
						multiple
						clearable
						ref="dispatchIdSelect"
						:disabled="formData.dispatchFlag !== '派单'"
					>
						<el-option
							v-for="item in userOptions"
							:key="item.id"
							:value="item.id"
							:label="item.username"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item prop="file" label="文件：" v-if="!fileId">
					<el-upload 
						ref="upload" 
						:limit="1"
						action="/api/monthlyMemo/saveStorageFileOne"
						accept="image/*, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .pdf, .txt, word, excel, pdf, txt, ppt" 
						:data="submitForm"
						:on-success="handleSubmitSuccess"
						:auto-upload="false"
						:file-list="fileList"
						:on-change="handleChange" 
						:on-remove="handleRemove">
          <el-button size="small" type="orange">上传文件</el-button>
        </el-upload>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>
<script>
import { $budgetAPI } from "@/api";
import { getCookie } from "@/common/js/cookie";
import { getSessionStorage } from "@/common/js/storage";
export default {
	components: {
		AreaCascader: () => import("./area_cascader.vue"),
	},
	data(){
		return {
			formData: {
				proTime: null,
				abStract: '',
				invAmt: '',
				invAmtThisYear: '',
				invAreaName: '',
				invAreaId: null,
				invSubCode: '',
				invIncomeType: '',
				invAcctMonth: '',
				moreInfo: '',
				admitPerson: '',
				eventTrigger: '',
				dispatchFlag: '',
				dispatchId: null,
			},
			rules: {
				proTime: [{required: true, message: '必填', trigger: 'change'}],
				abStract: [{required: true, message: '必填', trigger: 'change'}],
				invAmtThisYear: [{required: true, message: '必填', trigger: 'change'}],
				invAreaName: [{required: true, message: '必填', trigger: 'change'}],
				invAcctMonth: [{required: true, message: '必填', trigger: 'change'}],
				admitPerson: [{required: true, message: '必填', trigger: 'change'}],
				eventTrigger: [{required: true, message: '必填', trigger: 'change'}],
			},
			fileList: [],
			userOptions: [],
			submitForm: {},
			fileId: null,
		}
	},
	watch: {
		"formData.invAreaId"(val){
			this.formData.dispatchId = "";
			if(val) {
				this.getUser(val);	
			} else {
				this.userOptions = [];
			}
		},
		"formData.dispatchFlag"(val){
			if(val !== '派单') this.formData.dispatchId = "";
		}
	},
	created(){
		this.formData.admitPerson = getSessionStorage("userName");
		if(this.$route.query.seq){
			this.getData();
		}
	},
	methods: {
		getData() {
      this.fileId = this.$route.query.seq;

      $budgetAPI.monthlyMemoDetail(
        { fileId: this.$route.query.seq || this.fileId, token: getCookie("token") },
        (res) => {
          this.alertError(res);
          if (res.code == 0) {
						const { fileInfo } = res.content;
						this.formData.proTime = fileInfo.proTime;
						this.formData.abStract = fileInfo.abStract;
						this.formData.invAmt = fileInfo.invAmt;
						this.formData.invAmtThisYear = fileInfo.invAmtThisYear;
						this.formData.invAreaId = fileInfo.invAreaId;
						this.formData.invAreaName = fileInfo.invAreaName;
						this.formData.invSubCode = fileInfo.invSubCode;
						this.formData.invIncomeType = fileInfo.invIncomeType;
						this.formData.invAcctMonth = fileInfo.invAcctMonth;
						this.formData.moreInfo = fileInfo.moreInfo;
						this.formData.admitPerson = fileInfo.admitPerson;
						this.formData.eventTrigger = fileInfo.eventTrigger;
						this.formData.dispatchFlag = fileInfo.dispatchFlag;

						this.getUser(this.formData.invAreaId);
						this.$nextTick(() => {
							this.formData.dispatchId = fileInfo.dispatchId && fileInfo.dispatchId.split(",");
							this.$refs.areaCascader.$children[0].inputValue = fileInfo.invAreaName;
							this.$refs.areaCascader.$children[0].presentText = fileInfo.invAreaName;
						})
          }
        },
        (err) => {}
      );
    },
		getUser(areaId){
			$budgetAPI.monthlyMemoAreaUser(
        {
					areaId,
					token: getCookie("token"),
        },
				res => {
					if(res.code == 0){
						this.userOptions = res.content;
					}
				}
			)
		},
		async handle_submit(){
			await this.$refs.form.validate();
			this.submitForm = { ...this.formData };
			this.submitForm.dispatchAim = []
			this.submitForm.dispatchId && this.userOptions.forEach(it => {
				if(this.submitForm.dispatchId.some(id => id == it.id)){
					this.submitForm.dispatchAim.push(it.username);
				}
			})
			this.submitForm.dispatchAim = this.submitForm.dispatchAim.toString();
			this.submitForm.dispatchId = this.submitForm.dispatchId.toString();
			this.submitForm.token = getCookie("token");
			for(let it in this.submitForm){
				if(!this.submitForm[it]) delete this.submitForm[it]
			}
			//新增
			if(this.fileId == null){
				let formData = new FormData();
				Object.keys(this.submitForm).forEach(key => {
					formData.append(key, this.submitForm[key]);
				});
				this.fileList.forEach(item => {
					formData.append(`file`, item.raw);
				});
				$budgetAPI.addMonthlyMemo(formData, res => {
					if (res.code == 0) {
						this.$message.success("新增成功");
						this.$router.back();
					} else {
						this.$message.error(res.message);
					}
				})
			} else {
				//编辑
				this.submitForm.fileId = this.fileId;
				$budgetAPI.updateMonthlyMemo(this.submitForm, res => {
					if (res.code == 0) {
						this.$message.success("更新成功");
						this.$router.back();
					} else {
						this.$message.error(res.message);
					}
				})
			}
		},
    handleSubmitSuccess(res, file, fileList) {
      if (res.code == 0) {
        this.$message.success("新增成功");
        this.$router.back();
      } else {
        this.$message.error(res.message);
      }
    },
		handleChange(file, fileList) {
      this.fileList = fileList.slice(0);
    },
		handleRemove(file, fileList) {
      this.fileList = fileList.slice(0);
    },
	},
}
</script>
<style lang="scss" scoped>
.TopTitle {
    padding: 10px 18px 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #636d9a;
    border-bottom: 1px solid #eaeaea;
    .fl {
        > span {
            font-weight: bold;
            cursor: pointer;
        }
        > b {
            color: #7f92f7;
            font-weight: bolder;
            font-size: 15px;
        }
    }
}
.centerForm {
	display: flex;
	// align-items: center;
	justify-content: space-around;
	margin-top: 30px;
	/deep/ .el-input__inner {
		// height: 38px;
		// line-height: 38px;
		border-radius: 0;
		border: 1px solid #cdcfd9; /*#9799a5*/
		font-size: 12px;
		color: #333;
	}
	/deep/ .el-form-item__label {
			font-size: 13px;
			padding: 0;
			line-height: 32px !important;
	}
}
</style>